from django.conf import settings
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.contrib.auth.views import redirect_to_login
from django.db.models import Max, Q
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404
from django.template.defaultfilters import slugify
from django.urls import reverse
from django.views.generic import DetailView, ListView, TemplateView, FormView
from django.views.generic.edit import CreateView, DeleteView, UpdateView
import sys

from .models import Artist, Album, Song, ArtistAdmin, Queue, Rating


class ArtistsView(ListView):
    template_name = 'website/artists.html'
    context_object_name = 'artists'

    def get_queryset(self):
        return Artist.objects.all().order_by('name')


class ArtistView(DetailView):
    model = Artist
    template_name = 'website/artist.html'
    pk_url_kwarg = 'artist_handle'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['albums'] = Album.objects.filter(artist=self.kwargs['artist_handle']).order_by('release_date')
        if(self.request.user.is_authenticated):
            context['member'] = ArtistAdmin.objects.filter(artist=self.kwargs['artist_handle'], admin=self.request.user).exists()
        else:
            context['member'] = False
        return context


class ArtistCreate(LoginRequiredMixin, CreateView):
    model = Artist
    fields = ['name', 'handle']
    template_name = 'website/artist_create.html'

    def form_valid(self, form):
        a = form.save()
        ArtistAdmin.objects.create(admin=self.request.user, artist=a)
        return HttpResponseRedirect(reverse('artist', kwargs={'artist_handle': a.handle}))


class ArtistUpdate(UserPassesTestMixin, UpdateView):
    model = Artist
    fields = ['name', 'bio', 'logo']
    template_name = 'website/artist_update.html'
    pk_url_kwarg = 'artist_handle'
    raise_exception = True

    # Only allow band members to edit the Artist page
    def test_func(self):
        if self.request.user.is_authenticated:
            return ArtistAdmin.objects.filter(artist=self.kwargs['artist_handle'], admin=self.request.user).exists()
        else:
            return False


class ArtistDelete(UserPassesTestMixin, DeleteView):
    model = Artist
    tempate_name = 'website/artist_confirm_delete.html'
    pk_url_kwarg = 'artist_handle'
    raise_exception = True
    success_url = '/artists'

    # Only allow band members to edit the Artist page
    def test_func(self):
        if self.request.user.is_authenticated:
            return ArtistAdmin.objects.filter(artist=self.kwargs['artist_handle'], admin=self.request.user).exists()
        else:
            return False

class AlbumView(UpdateView):
    model = Album
    template_name = 'website/album.html'
    fields = []

    def get_queryset(self):
        self.artist = get_object_or_404(Artist, handle=self.kwargs['artist_handle'])
        return Album.objects.filter(handle=artist_handle)

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        if(self.request.user.is_authenticated):
            context['songs'] = Song.objects.filter(artist=self.kwargs['artist_handle'], album__slug__contains=self.kwargs['album_slug']).order_by('track').annotate(ind_rating=Max('rating__rating', filter=Q(rating__user=self.request.user)))
        else:
            context['songs'] = Song.objects.filter(artist=self.kwargs['artist_handle'], album__slug__contains=self.kwargs['album_slug']).order_by('track')
        context['queued_songs'] = Queue.objects.filter(song__artist__handle__contains=self.kwargs['artist_handle'], song__album__slug__contains=self.kwargs['album_slug']).values_list('song', flat=True)
        
        if(self.request.user.is_authenticated):
            context['member'] = ArtistAdmin.objects.filter(artist=self.kwargs['artist_handle'], admin=self.request.user).exists()
        else:
            context['member'] = False
        return context

    def get_object(self):
        return get_object_or_404(Album, slug=self.kwargs['album_slug']) 

    def form_valid(self, form):
        for k in self.request.POST:
            if not (k == 'csrfmiddlewaretoken'):
                song = Song.objects.get(slug=k)        

        if self.request.user.is_authenticated:
            button = self.request.POST.get(k)
            if(button=='Request'):
                q = Queue(song=song, requester=self.request.user)
                q.save()
            else:
                try:
                    r = Rating.objects.get(song=song, user=self.request.user)
                    r.rating = int(button)
                except ObjectDoesNotExist:
                    r = Rating(song=song, user=self.request.user, rating=int(button))
                r.save()

        self.success_url = self.request.path
        return super().form_valid(form)

class AlbumCreate(UserPassesTestMixin, CreateView):
    model = Album
    fields = ['title', 'cover', 'license', 'release_date']
    template_name = 'website/album_create.html'
    
    # Only allow band members to create/edit/delete album pages
    def test_func(self):
        if self.request.user.is_authenticated:
            return ArtistAdmin.objects.filter(artist=self.kwargs['artist_handle'], admin=self.request.user).exists()
        else:
            return False

    def form_valid(self, form):
        a = form.save(commit=False)
        a.artist = get_object_or_404(Artist, handle=self.kwargs['artist_handle'])
        a.slug = slugify(a.title)
        a.save()
        return HttpResponseRedirect(reverse('album', kwargs={'artist_handle': a.artist.handle, 'album_slug': a.slug}))


class SongAdd(UserPassesTestMixin, CreateView):
    model = Song
    fields = ['title', 'license', 'nsfw', 'file']
    template_name = 'website/song_add.html'

    # Only allow band members to create/edit/delete album pages
    def test_func(self):
        if self.request.user.is_authenticated:
            return ArtistAdmin.objects.filter(artist=self.kwargs['artist_handle'], admin=self.request.user).exists()
        else:
            return False

    def form_valid(self, form):
        a = form.save(commit=False)
        a.artist = get_object_or_404(Artist, handle=self.kwargs['artist_handle'])
        a.album = get_object_or_404(Album, slug=self.kwargs['album_slug'])
        a.slug = slugify(a.title)
        a.release_date = a.album.release_date
        a.save()
        return HttpResponseRedirect(reverse('album', kwargs={'artist_handle': a.artist.handle, 'album_slug': a.album.slug}))


class QueueAdd(LoginRequiredMixin, CreateView):
    model = Queue


class IndexView(TemplateView):
    template_name = 'website/index.html'


class NavbarView(TemplateView):
    template_name = 'website/navbar.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['radio_url1'] = settings.RADIO_URL1
        context['radio_url2'] = settings.RADIO_URL2
        context['radio_url3'] = settings.RADIO_URL3
        return context

class WelcomeView(TemplateView):
    template_name = 'website/welcome.html'
